/**
 * @author: Jam
 * @create: 2018-03-26 16:46
 */
package com.byxy.dao.impl;

import com.byxy.dao.AdminUserDao;
import com.byxy.model.AdminGroup;
import com.byxy.model.AdminUser;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class AdminUserDaoImpl implements AdminUserDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void save(AdminUser adminUser) {
        sessionFactory.getCurrentSession().save(adminUser);
    }

    @Override
    public void delete(Integer id) {
        AdminUser adminUser = (AdminUser) sessionFactory.getCurrentSession().load(AdminUser.class, id);
        sessionFactory.getCurrentSession().delete(adminUser);
    }

    @Override
    public void update(AdminUser adminUser) {
        sessionFactory.getCurrentSession().update(adminUser);
    }

    @Override
    public AdminUser get(Integer id) {
        return (AdminUser) sessionFactory.getCurrentSession().load(AdminUser.class, id);
    }

    @Override
    public List<AdminUser> listPage(Integer pageNum, Integer pageSize, String search) {
        //language=HQL
        String hql = "FROM AdminUser WHERE username LIKE :search";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter("search", "%".concat(search).concat("%"));
        if (pageNum > 0 && pageSize > 0) {
            query.setFirstResult((pageNum - 1) * pageSize);
            query.setMaxResults(pageSize);
        }
        return query.list();
    }

    @Override
    public Integer count(String search) {
        //language=HQL
        String hql = "SELECT COUNT(*) FROM AdminUser WHERE username LIKE :search";
        return ((Long) sessionFactory.getCurrentSession().createQuery(hql)
                .setParameter("search", "%".concat(search).concat("%"))
                .uniqueResult())
                .intValue();
    }

    @Override
    public List<AdminGroup> listGroup() {
        //language=HQL
        String hql = "FROM AdminGroup";
        return sessionFactory.getCurrentSession().createQuery(hql).list();
    }

    @Override
    public AdminUser login(String username, String password) {
        //language=HQL
        String hql = "FROM AdminUser WHERE username = ? AND password = ?";
        return (AdminUser) sessionFactory.getCurrentSession().createQuery(hql)
                .setParameter(0, username)
                .setParameter(1, password)
                .uniqueResult();
    }
}
